import { createApp, h } from 'vue';
import LoginModal from '@/components/LoginModal.vue';

let instance;

export const LoginService = {
  // 显示登录弹窗
  show(options = {}) {
    return new Promise((resolve) => {
      // 如果已经有实例，先移除
      if (instance) {
        document.body.removeChild(instance.el);
        instance.unmount();
        instance = null;
      }
      
      // 创建一个div作为容器
      const container = document.createElement('div');
      
      // 创建实例
      const app = createApp({
        render() {
          return h(LoginModal, {
            ref: 'loginModalRef',
            onClose: (result) => {
              resolve(result);
            }
          });
        }
      });
      
      // 挂载实例
      instance = app.mount(container);
      document.body.appendChild(container);
      
      // 打开弹窗
      instance.$refs.loginModalRef.open((success, userData) => {
        resolve({ success, userData });
        
        // 延迟移除DOM，等待动画完成
        setTimeout(() => {
          if (instance) {
            document.body.removeChild(container);
            app.unmount();
            instance = null;
          }
        }, 300);
      });
    });
  }
};

// 添加到Vue全局属性
export default {
  install(app) {
    app.config.globalProperties.$login = LoginService;
  }
}; 